<script setup>
import router from "@/router/index.js";
import {onMounted, reactive, ref} from "vue";
import {
  ojQuestionDetailService, ojQuestionExecuteResultService,
  ojQuestionNextDetailService,
  ojQuestionPrevDetailService,
  ojQuestionSubmitCodeByRocketMQService
} from "@/api/question.js";
import {useRoute} from "vue-router";
import {ArrowLeft, ArrowRight} from '@element-plus/icons-vue'
import codeEditor from "@/components/base/CodeEditor.vue";
import {
  finishContestService,
  firstQuestionContestService,
  nextQuestionContestService,
  prevQuestionContestService
} from "@/api/contest.js";
import {ElMessage} from "element-plus";

function goBack() {
  router.go(-1)
}

function convertTime(timeInMs) {
  return Math.floor(timeInMs / 1000);
}

function convertSpace(spaceInBytes) {
  return Math.floor(spaceInBytes / (1024 * 1024));
}

// 获取url中的OJ题目ID
let questionId = useRoute().query.questionId;
let examId = useRoute().query.contestId
let examTitle = useRoute().query.contestTitle || "";
let examEndTime = useRoute().query.contestEndTime

const defaultCodeRef = ref()
const questionDetail = reactive({})


async function getOjQuestion() {
  if (examId && (questionId == null || questionId == '')) {
    const result = await firstQuestionContestService(examId)
    console.log(result)
    questionId = result.data.id
  }
  let id = questionId
  const result = await ojQuestionDetailService(id)
  Object.assign(questionDetail, result.data)
  defaultCodeRef.value.setAceCode(questionDetail.defaultCode)
}

onMounted(() => {
  getOjQuestion()
})

const OjQuestionSubmitRespDTO = reactive({
  pass: 2,  //默认值设置为2，代表未提交代码
  percent: '', // 通过多少百分比
  executeMessage: '',  // 执行结果
  executeOutputCaseResult: [],  // 实际通过的测试用例
})

async function prevQuestion() {
  if (examId) {
    // 去请求竞赛中的OJ题目上一题
    const form = reactive({
      contestId: examId,
      questionId: questionId
    })
    const result = await prevQuestionContestService(form)
    questionId = result.data.id
  } else {
    const result = await ojQuestionPrevDetailService(questionId)
    if (result.data && result.data.id) {
      questionId = result.data.id;
    }
  }
  await getOjQuestion()
}

async function nextQuestion() {
  if (examId) {
    // 去请求竞赛中的OJ题目下一题
    const form = reactive({
      contestId: examId,
      questionId: questionId
    })
    const result = await nextQuestionContestService(form)
    questionId = result.data.id
  } else {
    const result = await ojQuestionNextDetailService(questionId)
    if (result.data && result.data.id) {
      questionId = result.data.id;
    }
  }
  await getOjQuestion()
}

function handleCountdownFinish() {
  ElMessage.info("当前竞赛已结束！")
  router.push("/user/system/contest")
}

// 默认Java代码
const submitForm = reactive({
  contestId: "",
  questionId: "",
  codeType: 0,
  userSubmitCode: ""
})

// 提交代码时间
let currentTime;
// 每次获取结果轮询间隔
const pollingInterval = ref(null);

// 提交代码逻辑
async function submitQuestion() {
  if (examId) {
    submitForm.contestId = examId
  }
  submitForm.questionId = questionId
  // 先提交代码到 mq
  await ojQuestionSubmitCodeByRocketMQService(submitForm)
  currentTime = new Date().toLocaleString();
  // 将当前代码判题状态改为执行中
  OjQuestionSubmitRespDTO.pass = 3
  // 前端启动定时器，轮询获取判题结果
  startPolling()
}

function startPolling() {
  stopPolling(); // 停止之前的轮询
  pollingInterval.value = setInterval(() => {
    getQuestionResult();
  }, 2000); // 每隔2秒请求一次
}

// 实际获取判题结果功能
async function getQuestionResult() {
  try {
    const executeForm = reactive({
      contestId: submitForm.contestId,
      questionId: submitForm.questionId,
      codeType: submitForm.codeType,
      currentTime: currentTime,
    });
    const res = await ojQuestionExecuteResultService(executeForm);
    Object.assign(OjQuestionSubmitRespDTO, {
      pass: res.data.pass,
      percent: res.data.percent,
      executeMessage: res.data.executeMessage,
      executeOutputCaseResult: res.data.executeOutputCaseResult || [],
    });
    if (OjQuestionSubmitRespDTO.pass !== 3) {
      stopPolling();
    }
  } catch (error) {
    console.error("获取判题结果出错：", error);
    stopPolling();
  }
}

function stopPolling() {
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value);
    pollingInterval.value = null;
  }
}

// 当编译器变化的时候，进行赋值
function handleEditorContent(userCode) {
  submitForm.userSubmitCode = userCode
}

const dialogVisible = ref(false);
const customTitle = ref('确认完成竞赛');

async function handleConfirm() {
  dialogVisible.value = false;
  // 发送完成竞赛请求
  await finishContestService(examId)
  goBack()
}
</script>

<template>
  <div class="page praticle-page flex-col">
    <div class="box_1 flex-row">
      <div class="group_1 ">
        <img class="label_4" src="@/assets/images/liebiao.png"/>
        <span class="label_5">{{ !examTitle ? '精选题库' : examTitle }}</span>
        <el-countdown v-if="examEndTime && new Date() < new Date(examEndTime)" class="exam-time-countdown"
                      @finish="handleCountdownFinish" title="距离竞赛结束还有:" :value="new Date(examEndTime)"/>
      </div>
      <div class="group_2">
        <el-button type="primary" plain @click="submitQuestion">提交代码</el-button>
        <el-button v-if="examId" type="primary" plain @click="dialogVisible = true">完成竞赛</el-button>
      </div>
      <el-button class="ide-back" type="text" @click="goBack()">返回</el-button>
    </div>
    <div class="box_8 flex-col">
      <div class="group_12 flex-row justify-between">
        <div class="image-wrapper_1 flex-row">
          <img class="thumbnail_2" src="@/assets/images/xiaobiaoti.png"/>
          <div class="question-nav">
            <span>题目描述</span>
          </div>
          <el-button
              type="primary"
              size="medium"
              class="question-nav-button"
              @click="prevQuestion">
            <el-icon>
              <ArrowLeft/>
            </el-icon>
            <span>上一题</span>
          </el-button>
          <el-button
              type="primary"
              size="medium"
              class="question-nav-button"
              @click="nextQuestion">
            <el-icon>
              <ArrowRight/>
            </el-icon>
            <span>下一题</span>
          </el-button>
        </div>
        <div class="image-wrapper_2 flex-row">
          <img class="image_1" src="@/assets/images/daima.png"/>
          代码
        </div>
      </div>
      <div class="group_13 flex-row justify-between">
        <div class="box_3 flex-col">
          <span class="question-title">{{ questionDetail.title }}</span>
          <span class="question-limit">
            <div class="difficulty">
              <span
                  v-if="questionDetail.difficulty === 0"
                  class="difficulty-tag easy">简单
              </span>
              <span
                  v-if="questionDetail.difficulty === 1"
                  class="difficulty-tag medium">中等
              </span>
              <span
                  v-if="questionDetail.difficulty === 2"
                  class="difficulty-tag hard">困难
              </span>
            </div>
            <div class="constraints">
              <span class="time-limit">
                时间限制：{{ convertTime(questionDetail.timeLimit) }} 秒
              </span>
              <span class="space-limit">
                空间限制：{{ convertSpace(questionDetail.spaceLimit) }} M
              </span>
            </div>
          </span>
          <span class="question-content" v-html="questionDetail.content"></span>
        </div>
        <div class="group_14 flex-col">
          <div class="group_8 flex-col">
            <codeEditor ref="defaultCodeRef" @update:value="handleEditorContent">
            </codeEditor>
          </div>
          <div class="code-result flex-row">
            <img class="code-result-image" src="@/assets/images/codeResult.png"/>
            <span class="code-result-content">执行结果</span>
          </div>
          <div class="group_15 flex-row">
            <div class="section_1 flex-row">
              <div class="section_3 flex-col">
                <div class="text-wrapper_2 flex-row justify-between">
                  <span class="text_1 red" v-if="OjQuestionSubmitRespDTO.pass === 0">未通过
                    <span class="percent-text">（{{ OjQuestionSubmitRespDTO.percent || 0 }}% 测试用例通过）</span>
                  </span>
                  <span class="text_1 success" v-if="OjQuestionSubmitRespDTO.pass === 1">通过
                    <span class="percent-text">（{{ OjQuestionSubmitRespDTO.percent || 0 }}% 测试用例通过）</span>
                  </span>
                  <span class="text_1 warning" v-if="OjQuestionSubmitRespDTO.pass === 2">请先执行代码</span>
                  <span class="text_1 info" v-if="OjQuestionSubmitRespDTO.pass === 3">系统正在处理您的代码，请稍后</span>
                </div>
                <span class="error-text" v-if="OjQuestionSubmitRespDTO.pass === 0">异常信息：{{
                    OjQuestionSubmitRespDTO.executeMessage
                  }}</span>
                <el-table
                    v-if="OjQuestionSubmitRespDTO.executeOutputCaseResult && OjQuestionSubmitRespDTO.executeOutputCaseResult.length > 0"
                    :data="OjQuestionSubmitRespDTO.executeOutputCaseResult" style="width: 100%;margin-bottom: 5px">
                  <el-table-column prop="input" label="输入"/>
                  <el-table-column prop="outPut" label="预期结果"/>
                  <el-table-column prop="actualOutPut" label="实际输出"/>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 完成竞赛功能提交框显示-->
  <el-dialog v-model="dialogVisible" :title="customTitle" width="20%">
    <span>请您确定所有题目代码均已提交，未提交代码会丢失哦！</span>
    <span class="dialog-footer">
      <el-button class="dialog-button" @click="dialogVisible = false">取消</el-button>
      <el-button class="dialog-button" type="primary" @click="handleConfirm">确认</el-button>
    </span>
  </el-dialog>
</template>

<style lang="scss" scoped>
.praticle-page {
  margin-top: 5px;

  .box_1 {
    background-color: rgba(240, 240, 240, 1);
    height: 60px;
    display: flex;
    align-items: center;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;

    /* 垂直居中 */

    .box_1 span {
      margin-right: 10px;
      /* 文字与图片之间的间距 */
    }

    .exam-time-countdown {
      margin: 0 0 0 400px;
    }

    .group_1 {
      display: flex;
      align-items: center;

      img {
        margin-right: 10px;
      }
    }

    .thumbnail_1 {
      width: 1px;
      height: 20px;
      margin: 20px 0 0 8px;
    }

    .label_4 {
      width: 26px;
      height: 26px;
    }

    .label_5 {
      margin-left: 10px;
    }

    .group_2 {
      margin-left: 600px;
      display: flex; /* 设为弹性布局 */
      gap: 30px; /* 调整按钮之间的间距 */
    }

    .group_3 {
      cursor: pointer;
      background-color: rgba(7, 126, 255, 0.1);
      border-radius: 0px 6px 6px 0px;
      width: 100px;
      height: 40px;
      margin: 10px 0 0 2px;
      font-size: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .ide-back {
      cursor: pointer;
      background-color: #f5f5f5;
      color: #333333;
      border: 1px solid #cccccc;
      padding: 8px 16px;
      border-radius: 4px;
      transition: all 0.3s ease;
      margin-right: 30px;
    }

    .ide-back:hover {
      background-color: #e0e0e0;
      color: #000000;
    }

    .ide-back:active {
      background-color: #cccccc;
      transform: scale(0.95);
    }

    .label_2 {
      width: 30px;
      height: 30px;
      margin: 15px 0 0 500px;
    }

    .label_3 {
      width: 30px;
      height: 30px;
      margin: 15px 70px 0 30px;
    }
  }
}

.page {
  background-color: rgba(247, 247, 247, 1);
  position: relative;
  height: 1010px;
  overflow: hidden;

  .box_8 {
    position: relative;
    width: 100%;
    height: 1451px;
    margin-bottom: 1px;

    .group_12 {
      width: 100%;
      height: 64px;
      margin-top: 10px;

      .image-wrapper_1 {
        background-color: rgba(240, 240, 240, 1);
        border-radius: 10px 10px 0px 0px;
        height: 64px;
        width: 612px;
        display: flex;
        align-items: center;
        /* 垂直居中 */

        .thumbnail_2 {
          width: 14px;
          height: 15px;
          margin: 0 10px 0 19px;
        }

        .question-nav {
          cursor: pointer;
          margin-right: 100px;
          display: flex;
          align-items: center;
        }

        .question-nav-button {
          margin-right: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #409eff; /* 默认文字颜色 */
          background-color: #ecf5ff; /* 默认背景颜色 */
          border: 1px solid #a7d1fd; /* 默认边框颜色 */
          border-radius: 4px; /* 按钮圆角 */
          padding: 6px 12px; /* 按钮内边距 */
        }

        .question-nav-button.active-button {
          background-color: #409eff; /* 点击后背景颜色 */
          color: #ffffff; /* 点击后文字颜色 */
          border-color: #409eff; /* 点击后边框颜色 */
        }

        .question-nav-button.active-button:hover {
          background-color: #66b1ff; /* 点击后悬停背景颜色 */
        }

      }

      .image-wrapper_2 {
        background-color: rgba(240, 240, 240, 1);
        border-radius: 10px 10px 0px 0px;
        height: 64px;
        display: flex;
        margin-left: 12px;
        align-items: center;
        flex: 1;
        /* 垂直居中 */

        .image_1 {
          width: 21px;
          height: 16px;
          margin: 0 10px 0 19px;
        }
      }
    }

    .group_13 {
      height: 904px;

      .box_3 {
        background-color: rgba(255, 255, 255, 1);
        border-radius: 10px;
        height: 860px;
        width: 610px;
        margin-right: 10px;
        overflow-y: auto; /* 启用垂直滚动 */
        overflow-x: hidden; /* 禁用水平滚动 */
        box-sizing: border-box; /* 确保内边距和边框不会导致内容溢出 */

        .question-title {
          font-weight: bold;
          font-size: 22px;
          margin-top: 20px;
          margin-left: 20px;
          margin-bottom: 10px;
        }

        .question-limit {
          font-size: 18px;
          color: #abaeac;
          margin-left: 20px;
          display: flex; /* 使用flex布局确保在同一行 */
          align-items: center; /* 垂直居中对齐 */
        }

        .difficulty {
          margin-right: 20px; /* 与时间和空间限制保持间距 */
        }

        .difficulty-tag {
          padding: 5px 10px;
          border-radius: 4px;
          font-size: 16px;
          font-weight: bold;
          display: inline-block;
        }

        .difficulty-tag.easy {
          background-color: #d4edda; /* 绿色背景 */
          color: #155724;
        }

        .difficulty-tag.medium {
          background-color: #fff3cd; /* 黄色背景 */
          color: #856404;
        }

        .difficulty-tag.hard {
          background-color: #f8d7da; /* 红色背景 */
          color: #721c24;
        }

        .constraints {
          font-size: 16px;
          color: #6c757d;
          display: flex; /* 使用flex布局来分隔时间限制和空间限制 */
          gap: 20px; /* 两者之间增加间距 */
        }

        .time-limit,
        .space-limit {
          display: inline-block; /* 保证两部分在一行 */
        }

        .question-content {
          font-size: 17px;
          margin-left: 20px;
        }

        .group_6 {
          background-color: rgba(241, 241, 241, 1);
          width: 21px;
          height: 874px;
          justify-content: center;
          margin: 10px 0 0 923px;

          .thumbnail_3 {
            width: 9px;
            height: 6px;
            margin: 10px 0 0 6px;
          }

          .group_7 {
            background-color: rgba(192, 192, 192, 1);
            width: 16px;
            height: 296px;
            margin: 10px 0 0 3px;
          }

          .thumbnail_4 {
            width: 9px;
            height: 6px;
            margin: 536px 0 10px 6px;
          }
        }
      }

      .group_14 {
        height: 904px;
        display: flex;
        width: calc(100vw - 663px);

        .group_8 {
          background-color: rgba(255, 255, 255, 1);
          border-radius: 10px;
          flex: 1;

          .thumbnail_5 {
            width: 11px;
            height: 6px;
            margin: 31px 0 0 69px;
          }

          .block_1 {
            width: 21px;
            height: 710px;
            border: 1px solid rgba(241, 241, 241, 1);
            margin: 19px 0 0 923px;
          }

          .image_2 {
            width: calc(100vw - 663px);
            height: 1px;
            margin: -710px 0 763px 0;
          }
        }

        .code-result {
          background-color: rgba(240, 240, 240, 1);
          border-radius: 10px 10px 0px 0px;
          height: 44px;
          margin-top: 10px;
          width: calc(100vw - 663px);

          .code-result-image {
            width: 27px;
            height: 27px;
            margin: 10px 0 0 20px;
          }

          .code-result-content {
            margin: 12px 0 0 15px;
          }
        }
      }
    }

    .group_15 {
      width: calc(100vw - 663px);
      height: 462px;

      .section_1 {
        background-color: rgba(255, 255, 255, 1);
        border-radius: 0px 0px 10px 10px;
        width: 100%;
        height: 330px;
        overflow-y: auto; /* 启用垂直滚动 */
        overflow-x: hidden; /* 禁用水平滚动 */
        box-sizing: border-box; /* 确保内边距和边框不会导致内容溢出 */

        .section_3 {
          width: 100%;
          height: 286px;
          margin: 10px 0 0 20px;

          .error-text {
            padding: 6px 20px;
            font-size: 14px;
            color: #666;
            background: #f7f7f7;
            border-left: 2px solid red;
            width: 100%;
          }

          .text-wrapper_2 {
            width: 217px;
            height: 40px;

            .text_1 {
              width: 60px;
              height: 40px;
              overflow-wrap: break-word;
              color: rgba(7, 126, 255, 1);
              font-size: 20px;
              font-family: MicrosoftYaHei;
              font-weight: normal;
              text-align: left;
              white-space: nowrap;
              line-height: 40px;

              .percent-text {
                margin-left: 5px; /* 与主文字保持一定间距 */
                color: #999; /* 较浅的颜色，用于区分主要状态 */
                font-size: 14px; /* 字体稍小 */
              }

              &.red {
                color: red;
              }

              &.info {
                color: #32C5FF;
              }

              &.success {
                color: green;
              }

              &.warning {
                color: orange;
              }
            }

            .text_2 {
              width: 137px;
              height: 24px;
              overflow-wrap: break-word;
              color: rgba(153, 153, 153, 1);
              font-size: 18px;
              font-family: MicrosoftYaHei;
              font-weight: normal;
              text-align: left;
              white-space: nowrap;
              line-height: 24px;
              margin-top: 13px;
            }
          }

          .box_9 {
            width: 382px;
            height: 50px;
            margin-top: 10px;

            .box_5 {
              background-color: rgba(242, 243, 245, 1);
              border-radius: 8px;
              width: 100px;
              height: 40px;

              .section_2 {
                background-color: rgba(7, 126, 255, 1);
                border-radius: 50%;
                width: 5px;
                height: 5px;
                margin: 23px 0 0 24px;
              }

              .text_3 {
                width: 63px;
                height: 26px;
                overflow-wrap: break-word;
                color: rgba(34, 34, 34, 1);
                font-size: 15px;
                font-family: MicrosoftYaHei;
                font-weight: normal;
                text-align: right;
                white-space: nowrap;
                line-height: 26px;
                margin: 10px 4px 0 0;
              }
            }

            .box_6 {
              background-color: rgba(153, 153, 153, 1);
              border-radius: 50%;
              width: 5px;
              height: 5px;
              margin: 23px 0 0 44px;
            }

            .text_4 {
              width: 63px;
              height: 26px;
              overflow-wrap: break-word;
              color: rgba(153, 153, 153, 1);
              font-size: 20px;
              font-family: MicrosoftYaHei;
              font-weight: normal;
              text-align: right;
              white-space: nowrap;
              line-height: 26px;
              margin: 12px 0 0 6px;
            }

            .box_7 {
              background-color: rgba(153, 153, 153, 1);
              border-radius: 50%;
              width: 5px;
              height: 5px;
              margin: 23px 0 0 68px;
            }

            .text_5 {
              width: 63px;
              height: 26px;
              overflow-wrap: break-word;
              color: rgba(153, 153, 153, 1);
              font-size: 20px;
              font-family: MicrosoftYaHei;
              font-weight: normal;
              text-align: right;
              white-space: nowrap;
              line-height: 26px;
              margin: 12px 0 0 6px;
            }
          }

          .text_6 {
            width: 40px;
            height: 26px;
            overflow-wrap: break-word;
            color: rgba(102, 102, 102, 1);
            font-size: 20px;
            font-family: MicrosoftYaHei;
            font-weight: normal;
            text-align: right;
            white-space: nowrap;
            line-height: 26px;
            margin-top: 24px;
          }

          .block_4 {
            background-color: rgba(242, 243, 245, 1);
            border-radius: 8px;
            width: 883px;
            height: 106px;
            margin-top: 16px;
          }
        }

        .block_5 {
          background-color: rgba(241, 241, 241, 1);
          width: 20px;
          height: 422px;
          justify-content: center;
          margin: 10px 1px 0 20px;

          .thumbnail_7 {
            width: 9px;
            height: 6px;
            margin: 10px 0 0 6px;
          }

          .group_10 {
            background-color: rgba(192, 192, 192, 1);
            width: 16px;
            height: 296px;
            margin: 10px 0 0 3px;
          }

          .thumbnail_8 {
            width: 9px;
            height: 6px;
            margin: 84px 0 10px 6px;
          }
        }
      }
    }

    .group_11 {
      box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.06);
      background-color: rgba(255, 255, 255, 1);
      border-radius: 10px;
      position: absolute;
      left: 82px;
      top: -9px;
      width: 284px;
      height: 218px;
    }
  }
}

.dialog-footer {
  display: flex; /* 使用 Flex 布局 */
  justify-content: center; /* 居中对齐 */
  gap: 16px; /* 按钮之间的间距 */
  margin-top: 16px; /* 上边距 */
}

.dialog-button {
  width: 80px; /* 按钮宽度 */
}
</style>